package com.mmall.common;


import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.io.Serializable;

/**
 * 高复用服务响应对象
 * Created by qezhhnjy on 2017/9/21-23:53-23:57-23:57.
 * include指定返回json对象的类变量为非空类型,即不返回空字段.
 */
@JsonSerialize()
@JsonInclude(value = JsonInclude.Include.NON_EMPTY)
public class ServerResponse<T> implements Serializable {
    private int status;
    private String msg;
    private T data;

    private ServerResponse(int status, String msg, T data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    private ServerResponse(int status) {
        this(status, null, null);
    }

    private ServerResponse(int status, String msg) {
        this(status, msg, null);
    }

    //这个构造方法和上面那个构造方法，如果定义<T>为String类型,则无法定位构造方法.需要通过泛型方法二次调用来区分方法.
    private ServerResponse(int status, T data) {
        this(status, null, data);
    }

    public int getStatus() {
        return status;
    }

    public String getMsg() {
        return msg;
    }

    public T getData() {
        return data;
    }

    /**
     * 判断响应对象类型
     *
     * @return true/false
     * JsonIgnore配置返回信息不在json序列化结果当中
     */
    @JsonIgnore
    public boolean isSuccess() {
        return this.status == ResponseInfo.SUCCESS.getCode();
    }

    /**
     * 创建成功响应对象的四种方法
     *
     * @param <T> 　泛型
     * @return 响应对象
     */
    public static <T> ServerResponse<T> createBySuccess() {
        return new ServerResponse<T>(ResponseInfo.SUCCESS.getCode(), ResponseInfo.SUCCESS.getDescription());
    }

    public static <T> ServerResponse<T> createBySuccessMessage(String msg) {
        return new ServerResponse<T>(ResponseInfo.SUCCESS.getCode(), msg);
    }

    public static <T> ServerResponse<T> createBySuccess(T data) {
        return new ServerResponse<T>(ResponseInfo.SUCCESS.getCode(), data);
    }

    public static <T> ServerResponse<T> createBySuccess(String msg, T data) {
        return new ServerResponse<T>(ResponseInfo.SUCCESS.getCode(), msg, data);
    }

    /**
     * 创建失败响应对象
     *
     * @param <T> 泛型
     * @return 响应对象
     */
    //通用错误信息
    public static <T> ServerResponse<T> createByError() {
        return new ServerResponse<T>(ResponseInfo.ERROR.getCode(), ResponseInfo.ERROR.getDescription());
    }

    //指定错误信息
    public static <T> ServerResponse<T> createByErrorMessage(String msg) {
        return new ServerResponse<T>(ResponseInfo.ERROR.getCode(), msg);
    }

    //指定错误代码和信息
    public static <T> ServerResponse<T> createByErrorCode(int code, String msg) {
        return new ServerResponse<T>(code, msg);
    }
}
